package com.ltedu.oss.utils;

import com.aliyun.vod.upload.impl.UploadImageImpl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadImageRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: UploadVideoUtils
 * @auther: Jerry
 * @date: 2020/12/10 15:15
 * @desctiption: TODO
 * @version: 1.0
 */
@Component
public class UploadVideoUtils implements InitializingBean {

    private static Logger logger = LoggerFactory.getLogger(UploadVideoUtils.class);

    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${secret}")
    private String secret;
    /**
     * 账号AK信息（必选）
     */
    public static String AccessKey_ID;
    /**
     * 账号AK信息（必选）
     */
    public static String AccessKey_Secret;

    @Override
    public void afterPropertiesSet() throws Exception {
        AccessKey_ID = accessKeyId;
        AccessKey_Secret = secret;
    }

    /**
     * 上传视频
     *
     * @param title       标题
     * @param fileName    文件名称
     * @param inputStream 输入流
     * @return {@link String}
     */
    public static String uploadVideo(String title, String fileName, InputStream inputStream) {
        logger.info("UploadVideoUtils.uploadVideo...");
        UploadStreamRequest request = new UploadStreamRequest(AccessKey_ID, AccessKey_Secret,
                title, fileName, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        //请求视频点播服务的请求ID
        logger.info("UploadVideoUtils.uploadVideo...RequestId={}", response.getRequestId());
        if (response.isSuccess()) {
            logger.info("UploadVideoUtils.uploadVideo...VideoId={}", response.getVideoId());
        } else {
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            logger.info("UploadVideoUtils.uploadVideo...VideoId={}", response.getVideoId());
            logger.info("UploadVideoUtils.uploadVideo...ErrorCode={}", response.getCode());
            logger.info("UploadVideoUtils.uploadVideo...ErrorMessage={}", response.getMessage());
        }
        return response.getVideoId();
    }

    /**
     * 本地文件上传接口
     *
     * @param title
     * @param fileName
     */
    public static String uploadVideo(String title, String fileName) {
        UploadVideoRequest request = new UploadVideoRequest(AccessKey_ID, AccessKey_Secret, title, fileName);
        /*可指定分片上传时每个分片的大小，默认为1M字节*/
        request.setPartSize(1 * 1024 * 1024L);
        /*可指定分片上传时的并发线程数，默认为1（注：该配置会占用服务器CPU资源，需根据服务器情况指定）*/
        request.setTaskNum(1);
        /*是否开启断点续传，默认断点续传功能关闭。当网络不稳定或者程序崩溃时，再次发起相同上传请求，可以继续未完成的上传任务，适用于超时3000秒仍不能上传完成的大文件。
        注意: 断点续传开启后，会在上传过程中将上传位置写入本地磁盘文件，影响文件上传速度，请您根据实际情况选择是否开启*/
        request.setEnableCheckpoint(false);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        //请求视频点播服务的请求ID
        logger.info("UploadVideoUtils.UploadVideo...RequestId={}", response.getRequestId());
        if (response.isSuccess()) {
            logger.info("UploadVideoUtils.uploadVideo...VideoId={}", response.getVideoId());
        } else {
            /* 如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因 */
            logger.info("UploadVideoUtils.uploadVideo...VideoId={}", response.getVideoId());
            logger.info("UploadVideoUtils.uploadVideo...ErrorCode={}", response.getCode());
            logger.info("UploadVideoUtils.uploadVideo...ErrorMessage={}", response.getMessage());
        }
        return response.getVideoId();
    }



    /**
     * 图片上传接口，本地文件上传示例
     * 参数参考文档 https://help.aliyun.com/document_detail/55619.html
     *
     */
    public static Map<String, String> uploadImageLocalFile() {
        //图片类型（必选）取值范围：default（默认），cover（封面），watermark（水印）
        String imageType = "cover";
        UploadImageRequest request = new UploadImageRequest(AccessKey_ID, AccessKey_Secret, imageType);
        UploadImageImpl uploadImage = new UploadImageImpl();
        UploadImageResponse response = uploadImage.upload(request);
        logger.info("UploadVideoUtils.uploadImageLocalFile...RequestId={}", response.getRequestId());
        Map<String, String> imageMap = new HashMap<>();
        if (response.isSuccess()) {
            logger.info("UploadVideoUtils.uploadImageLocalFile...ImageId={}", response.getImageId());
            logger.info("UploadVideoUtils.uploadImageLocalFile...ImageURL={}", response.getImageURL());
            imageMap.put("imageId", response.getImageId());
            imageMap.put("imageURL", response.getImageURL());
        } else {
            logger.info("UploadVideoUtils.uploadImageLocalFile...ErrorCode={}", response.getCode());
            logger.info("UploadVideoUtils.uploadImageLocalFile...ErrorMessage={}", response.getMessage());
            imageMap.put("ErrorCode", response.getCode());
            imageMap.put("ErrorMessage", response.getMessage());
        }
        return imageMap;
    }
}
